﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DayPilot.Web.Ui;
using UTSDAL.LINQSQL.Views;
using UTSDAL.LINQSQL.DAO;
using UTSDAL.LINQSQL.Model;
using System.IO;
using log4net;
using System.IO.Compression;
using System.Security.AccessControl;
using ICSharpCode.SharpZipLib.Zip;

public partial class pages_admin_reporting : System.Web.UI.Page
{

    private static readonly ILog logger = LogManager.GetLogger(typeof(pages_admin_reporting));

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private TimetableEventDAO timetableEventDAO = new TimetableEventDAO();

    private SemesterDAO semesterDAO = new SemesterDAO();

    private CohortDAO cohortDAO = new CohortDAO();

    protected void DownloadAll_Click(object sender, EventArgs e)
    {
        DayPilotCalendar calendar = new DayPilotCalendar();

        ObjectUtils.initCalendar(calendar);

        calendar.DataStartField = "StartTime";
        calendar.DataEndField = "EndTime";
        calendar.DataTextField = "CalendarDisplayString";
        calendar.DataValueField = "TimetableEventId";
        

        Semester selectedSemester = SemesterDropDown.Semester;
        Cohort selectedCohort = CohortDropDown.Cohort;

        if (selectedCohort == null)
        {
            downloadAllTimetablesForSemester(selectedSemester, calendar);
        }
        else
        {
            downloadTimetableForCohort(selectedSemester, selectedCohort, calendar);
        }
    }


    private void downloadTimetableForCohort(Semester semester, Cohort cohort, DayPilotCalendar calendar)
    {

        List<TimetableEventView> views = timetableEventDAO.getTimetableEventsViewBySemesterAndCohort(semester,cohort);
        calendar.DataSource = views;
        calendar.DataBind();
        writeFile(calendar, cohort.CohortName, cohort.CohortName);
        StartZip(cohort.CohortName);
        downloadFiles(cohort.CohortName);

    }

    private void downloadAllTimetablesForSemester(Semester selectedSemester,DayPilotCalendar calendar)
    {
        List<Cohort> cohorts = cohortDAO.findCohortsBySemester(selectedSemester);
        createFolder(selectedSemester.SemesterName);

        foreach (Cohort cohort in cohorts)
        {
            List<TimetableEventView> views = timetableEventDAO.getTimetableEventsViewBySemesterAndCohort(selectedSemester, cohort);

            calendar.DataSource = views;
            calendar.DataBind();
            writeFile(calendar, selectedSemester.SemesterName, cohort.CohortName);
        }

        //compress(selectedSemester.SemesterName);

        StartZip(selectedSemester.SemesterName);
        downloadFiles(selectedSemester.SemesterName);
    }

    public void StartZip(string path)
    {

        String directory = Server.MapPath("~/downloads/" + path);
        String zipfile_path = directory + ".zip";

        logger.Debug("Directory = " + directory);
        // the directory you need to zip
        string[] filenames = Directory.GetFiles(directory);

        // path which the zip file built in
        ZipOutputStream s = new ZipOutputStream(File.Create(zipfile_path));
        foreach (string filename in filenames)
        {
            logger.Debug("File Name = " + filename);

            FileStream fs = File.OpenRead(filename);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);

            ZipEntry entry = new ZipEntry(Path.GetFileName(filename));
            s.PutNextEntry(entry);
            s.Write(buffer, 0, buffer.Length);
            fs.Close();

        }
        s.SetLevel(5);
        s.Finish();
        s.Close();
    }


    private void createFolder(String folderName)
    {
        
        // Specify a "currently active folder"
        string activeDir = Server.MapPath("~/downloads");

        //Create a new subfolder under the current active folder
        string newPath = System.IO.Path.Combine(activeDir, folderName);

        // Create the subfolder
        DirectoryInfo directoryInfo = new DirectoryInfo(activeDir);
        DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
        
        System.IO.Directory.CreateDirectory(@newPath,directorySecurity);

    }


    private void writeFile(DayPilotCalendar calendar, String folderName, String file)
    {

        createFolder(folderName);
        String fileName = Server.MapPath("~/downloads/" + folderName + "/" + file + ".html");
        

        FileInfo fileInfo = new FileInfo(fileName);
        logger.Debug("File Name = " + fileName);

        StreamWriter stringWriter = fileInfo.CreateText();
        HtmlTextWriter writer = new HtmlTextWriter(stringWriter);

        writer.InnerWriter.Write("<div style='text-align:center'>");
        writer.InnerWriter.Write("<h1>University of Technology Mauritius</h1>");
        writer.InnerWriter.Write("<h2>" + folderName + "</h2>");
        writer.InnerWriter.Write("<h3>" + file + "</h3>");
        writer.InnerWriter.Write("</div>");
        
        
        calendar.RenderControl(writer);

        writer.Flush();
        writer.Close();
    }

    private void downloadFiles(String folderName)
    {
        
        folderName = Server.MapPath("~/downloads/") + folderName + ".zip";
        

        Response.Write(folderName);
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(folderName));
        Response.ContentType = "application/x-zip-compressed";
        Response.WriteFile(folderName);
        Response.Flush();
        Response.Close();
    }
}
